package com.neusoft.serviceImpl;



import java.util.Date;
import java.util.List;

import com.neusoft.dao.CartDao;
import com.neusoft.dao.OrdersDao;
import com.neusoft.dao.OrdersDetailDao;
import com.neusoft.dao.ProductDao;
import com.neusoft.pojo.Cart;
import com.neusoft.pojo.Orders;
import com.neusoft.pojo.OrdersDetail;
import com.neusoft.pojo.Product;
import com.neusoft.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrdersServiceImpl implements OrdersService {

	@Autowired
	private OrdersDao ordersDao;
	@Autowired
	private ProductDao productDao;
	@Autowired
	private CartDao cartDao;
	@Autowired
	private OrdersDetailDao ordersDetailDao;
	
	//新增一条订单
	@Transactional
	public void addOrders(int uid,int ocost,String uname) {
		//新增一条订单
		Orders orders = new Orders();
		orders.setOcost(ocost);
		orders.setOcreatetime(new Date());
		orders.setUid(uid);
		orders.setUname(uname);
		ordersDao.insertOrders(orders);
		
		//新增订单中的订单详情记录
		OrdersDetail ordersDetail = null;
		List<Cart> cartList = cartDao.getCartListByUid(uid);
		for(Cart c : cartList) {
			ordersDetail = new OrdersDetail();
			ordersDetail.setOid(orders.getOid());
			ordersDetail.setPid(c.getPid());
			ordersDetail.setPname(c.getProduct().getPname());
			ordersDetail.setPquantity(c.getPquantity());
			ordersDetail.setPrice(c.getProduct().getPrice());
			ordersDetailDao.insertOrdersDetail(ordersDetail);
			//更新库存
			Product product = productDao.getProduct(c.getPid());
			productDao.updatePstock(product.getPstock()-1, c.getPid());
		}
		//清空购物车列表
		cartDao.emptyCart(uid);
		
	}

}
